[Manual] R语言quantstrat包使用手册

绕题太远了

Posted by Leung ZhengHua on 2018-02-02

本文总点击量

在阅读本文之前,你可能对以下扫盲贴有兴趣:

强烈推荐《Backtesting Strategies with R》
如何搭建量化投资研究系统之三(工具篇quantstrat)
Quantitative Trading Strategy Using Quantstrat Package in R: A Step by Step Guide
R Forge package 地址
A Hammer Trading System — Demonstrating Custom Indicator-Based Limit Orders in Quantstrat
一份你可能不太想阅读的QuantstratWorkshop.pdf


先来一段代码压压惊吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# _________________________________
# date: 2017-02-02
# version: 0.1
# backtesting-strategies learning
# 我们约定,注释中一个#表示一级标题;两个#表示二级标题
# 正文注释使用 # *** ¥%#……¥*@!***
# 你需要某些技术手段去翻墙,比如XXnet,好吧,其实没有人看这篇东西
# 因为要从google得到案例数据,yahoo已废
# 这个脚本完完全全是抄袭了《backtesting-strategies》中的前5章和第12章
# 你看,把这个脚本从头跑一遍就可以读掉了半本书
# 作者越往后写的文字越少,其实把代码全扒下来,剩下的东西也没什么营养了
# 我还会回来的
# ________________________________
# Chapter 1 Libraries
# *** 下面是你需要安装的包 ***
library(quantstrat)
library(data.table)
library(dplyr)
library(DT)
library(ggplot2)
library(htmltools)
library(htmlwidgets)
library(knitr)
library(lattice)
library(pander)
library(tidyr)
library(webshot)
# Chapter 2 Terminology
# *** BTO: Buy to Open (open long positions) ***
# *** BTC: Buy to close (close short positions) ***
# *** SL: Stop-limit order ***
# *** STO: Sell to open (open short positions) ***
# *** STC: Sell to close (close long positions) ***
# *** TS: Trailing-stop order ***
## 3.1 Settings and Variables
# *** 设定美帝的时区和货币种类 ***
Sys.setenv(TZ = "UTC")
currency('USD')
# *** 初始化起止日和账户资金 ***
init_date <- "2007-12-31"
start_date <- "2008-01-01"
end_date <- "2009-12-31"
init_equity <- 1e4 # $10,000
adjustment <- TRUE
## 3.2 Symbols
# *** 设定测试中所用的股票代码 ***
basic_symbols <- function() {
symbols <- c(
"IWM", # iShares Russell 2000 Index ETF
"QQQ", # PowerShares QQQ TRust, Series 1 ETF
"SPY" # SPDR S&P 500 ETF Trust
)
}
enhanced_symbols <- function() {
symbols <- c(
basic_symbols(),
"TLT", # iShares Barclays 20+ Yr Treas. Bond ETF
"XLB", # Materials Select Sector SPDR ETF
"XLE", # Energy Select Sector SPDR ETF
"XLF", # Financial Select Sector SPDR ETF
"XLI", # Industrials Select Sector SPDR ETF
"XLK", # Technology Select Sector SPDR ETF
"XLP", # Consumer Staples Select Sector SPDR ETF
"XLU", # Utilities Select Sector SPDR ETF
"XLV", # Health Care Select Sector SPDR ETF
"XLY" # Consumer Discretionary Select Sector SPDR ETF
)
}
global_symbols <- function() {
symbols <- c(
enhanced_symbols(),
"EFA", # iShares EAFE
"EPP", # iShares Pacific Ex Japan
"EWA", # iShares Australia
"EWC", # iShares Canada
"EWG", # iShares Germany
"EWH", # iShares Hong Kong
"EWJ", # iShares Japan
"EWS", # iShares Singapore
"EWT", # iShares Taiwan
"EWU", # iShares UK
"EWY", # iShares South Korea
"EWZ", # iShares Brazil
"EZU", # iShares MSCI EMU ETF
"IGE", # iShares North American Natural Resources
"IYR", # iShares U.S. Real Estate
"IYZ", # iShares U.S. Telecom
"LQD", # iShares Investment Grade Corporate Bonds
"SHY" # iShares 42372 year TBonds
)
}
## 3.3 checkBlotterUpdate()
# Guy Yollin, 2014
# http://www.r-programming.org/papers
checkBlotterUpdate <- function(port.st = portfolio.st,
account.st = account.st,
verbose = TRUE) {
ok <- TRUE
p <- getPortfolio(port.st)
a <- getAccount(account.st)
syms <- names(p$symbols)
port.tot <- sum(
sapply(
syms,
FUN = function(x) eval(
parse(
text = paste("sum(p$symbols",
x,
"posPL.USD$Net.Trading.PL)",
sep = "$")))))
port.sum.tot <- sum(p$summary$Net.Trading.PL)
if(!isTRUE(all.equal(port.tot, port.sum.tot))) {
ok <- FALSE
if(verbose) print("portfolio P&L doesn't match sum of symbols P&L")
}
initEq <- as.numeric(first(a$summary$End.Eq))
endEq <- as.numeric(last(a$summary$End.Eq))
if(!isTRUE(all.equal(port.tot, endEq - initEq)) ) {
ok <- FALSE
if(verbose) print("portfolio P&L doesn't match account P&L")
}
if(sum(duplicated(index(p$summary)))) {
ok <- FALSE
if(verbose)print("duplicate timestamps in portfolio summary")
}
if(sum(duplicated(index(a$summary)))) {
ok <- FALSE
if(verbose) print("duplicate timestamps in account summary")
}
return(ok)
}
# *** checkBlotterUpdate是用于检查账户和资产组合,如果返回FALSE,需要检查还有哪些账户和资产组合还在R的工作空间里 ***
# 4 Get Symbols
print(basic_symbols())
symbols <- basic_symbols()
# *** 我需要翻墙google才能使用getSymbols这个函数 ***
# *** getSymbols函数的作用是返回各个symbol(股票)的数据,每个symbol是一个数据框 ***
getSymbols(Symbols = symbols,
src = "google",
index.class = "POSIXct",
from = start_date,
to = end_date,
adjust = adjustment)
# *** 观察拉取的数据 ***
head(IWM)
tail(IWM)
chartSeries(SPY)
# 5 Basic Strategy
## 5.1 Strategy Setup
# *** 将需要交易的symbol用stock绑定到某工作空间 ***
stock(symbols,
currency = "USD",
multiplier = 1)
# *** 命名你的资产组合、账户名称和策略名称,以免你贵人多忘事 ***
portfolio.st <- "Port.Luxor"
account.st <- "Acct.Luxor"
strategy.st <- "Strat.Luxor"
# *** 保守起见,将历史上可能遗留在工作空间的资产组合和账户全部销毁 ***
rm.strat(portfolio.st)
rm.strat(account.st)
# *** 初始化资产组合和账户 ***
initPortf(name = portfolio.st,
symbols = symbols,
initDate = init_date)
initAcct(name = account.st,
portfolios = portfolio.st,
initDate = init_date,
initEq = init_equity)
initOrders(portfolio = portfolio.st,
symbols = symbols,
initDate = init_date)
strategy(strategy.st, store = TRUE)
## 5.2 Add Indicators
# *** 我们以双均线策略为例继续我们的练习 ***
# *** 短期均线SMA(10)上穿长期均线SMA(30)表明短期内会上涨,应买入 ***
# *** 短期均线SMA(10)下穿长期均线SMA(30)表明短期内会下跌,应卖出 ***
# *** add.indicator是一个给我们策略添加指标的函数 ***
# *** 具体地理解就是给每个股票的数据框增加一列指标 ***
# *** 比如SMA10,是最近10期价格的平均 ***
# *** name的输入应当是一个函数的名称,arguments是这个函数的输入参数 ***
# *** SMA这个函数来自TTR包 ***
# *** label标明了在数据集里增加的新的一列指标的名字 ***
# *** 可以看到最重要最复杂的是arguments ***
# *** 如果你想引用数据集中某一列,赋值给x,请参考 x=IWM$Close ***
# *** mktdata 是一个特殊的数据集,存储了我们的signal和indicator ***
# *** 当apply你的策略时,你可以看到最后一个symbol的mktdata ***
# *** Cl 是close的缩写,暂时可以忽略它***
add.indicator(strategy = strategy.st,
name = "SMA",
arguments = list(x = quote(Cl(mktdata)),
n = 10),
label = "nFast")
add.indicator(strategy = strategy.st,
name = "SMA",
arguments = list(x = quote(Cl(mktdata)),
n = 30),
label = "nSlow")
## 5.3 Add Signals
# *** 同上的解释 ***
add.signal(strategy = strategy.st,
name="sigCrossover",
arguments = list(columns = c("nFast", "nSlow"),
relationship = "gte"),
label = "long")
add.signal(strategy = strategy.st,
name="sigCrossover",
arguments = list(columns = c("nFast", "nSlow"),
relationship = "lt"),
label = "short")
## 5.4 Add Rules
# *** 同上的解释 ***
add.rule(strategy = strategy.st,
name = "ruleSignal",
arguments = list(sigcol = "long",
sigval = TRUE,
orderqty = 100,
ordertype = "stoplimit",
orderside = "long",
threshold = 0.0005,
prefer = "High",
TxnFees = -10,
replace = FALSE),
type = "enter",
label = "EnterLONG")
add.rule(strategy.st,
name = "ruleSignal",
arguments = list(sigcol = "short",
sigval = TRUE,
orderqty = -100,
ordertype = "stoplimit",
threshold = -0.005,
orderside = "short",
replace = FALSE,
TxnFees = -10,
prefer = "Low"),
type = "enter",
label = "EnterSHORT")
add.rule(strategy.st,
name = "ruleSignal",
arguments = list(sigcol = "short",
sigval = TRUE,
orderside = "long",
ordertype = "market",
orderqty = "all",
TxnFees = -10,
replace = TRUE),
type = "exit",
label = "Exit2SHORT")
add.rule(strategy.st,
name = "ruleSignal",
arguments = list(sigcol = "long",
sigval = TRUE,
orderside = "short",
ordertype = "market",
orderqty = "all",
TxnFees = -10,
replace = TRUE),
type = "exit",
label = "Exit2LONG")
# 5.5 Apply Strategy
# *** 执行你的策略,得到回测结果 ***
cwd <- getwd()
setwd("./_data/")
results_file <- paste("results", strategy.st, "RData", sep = ".")
if( file.exists(results_file) ) {
load(results_file)
} else {
results <- applyStrategy(strategy.st, portfolios = portfolio.st)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
if(checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)) {
save(list = "results", file = results_file)
save.strategy(strategy.st)
}
}
setwd(cwd)
# Chapter 12 Analyzing Results
## 12.1 Apply Strategy
# *** 这一小节实际上和前面重复了,可以不执行 ***
checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
## 12.2 Chart Positions
# *** 画出仓位走势图 ***
for(symbol in symbols) {
chart.Posn(portfolio.st, Symbol = symbol,
TA = "add_SMA(n = 10, col = 4); add_SMA(n = 30, col = 2)")
}
## 12.3 Trade Statistics
tstats <- tradeStats(portfolio.st)
kable(t(tstats))
### 12.3.1 Trade Related
tab.trades <- tstats %>%
mutate(Trades = Num.Trades,
Win.Percent = Percent.Positive,
Loss.Percent = Percent.Negative,
WL.Ratio = Percent.Positive/Percent.Negative) %>%
select(Trades, Win.Percent, Loss.Percent, WL.Ratio)
# 我自己加上去的,不然下一句报错the table must have a header (column names)
rownames(tab.trades)=c('stock1','stock2','stock3')
kable(t(tab.trades))
### 12.3.2 Profit Related
tab.profit <- tstats %>%
select(Net.Trading.PL, Gross.Profits, Gross.Losses, Profit.Factor)
kable(t(tab.profit))
### 12.3.3 Averages
tab.wins <- tstats %>%
select(Avg.Trade.PL, Avg.Win.Trade, Avg.Losing.Trade, Avg.WinLoss.Ratio)
kable(t(tab.wins))
### 12.3.4 Performance Summary
rets <- PortfReturns(Account = account.st)
rownames(rets) <- NULL
charts.PerformanceSummary(rets, colorset = bluefocus)
### 12.3.5 Per Trade Statistics
for(symbol in symbols) {
pts <- perTradeStats(portfolio.st, Symbol = symbol)
kable(pts, booktabs = TRUE, caption = symbol)
}
kable(pts)
### 12.3.6 Performance Statistics
tab.perf <- table.Arbitrary(rets,
metrics=c(
"Return.cumulative",
"Return.annualized",
"SharpeRatio.annualized",
"CalmarRatio"),
metricsNames=c(
"Cumulative Return",
"Annualized Return",
"Annualized Sharpe Ratio",
"Calmar Ratio"))
kable(tab.perf)
### 12.3.7 Risk Statistics
tab.risk <- table.Arbitrary(rets,
metrics=c(
"StdDev.annualized",
"maxDrawdown",
"VaR",
"ES"),
metricsNames=c(
"Annualized StdDev",
"Max DrawDown",
"Value-at-Risk",
"Conditional VaR"))
kable(tab.risk)
### 12.3.8 Buy and Hold Performance
rm.strat("buyHold")
# initialize portfolio and account
initPortf("buyHold", "SPY", initDate = init_date)
initAcct("buyHold", portfolios = "buyHold",
initDate = init_date, initEq = init_equity)
# place an entry order
CurrentDate <- time(getTxns(Portfolio = portfolio.st, Symbol = "SPY"))[2]
equity = getEndEq("buyHold", CurrentDate)
ClosePrice <- as.numeric(Cl(SPY[CurrentDate,]))
UnitSize = as.numeric(trunc(equity/ClosePrice))
addTxn("buyHold", Symbol = "SPY", TxnDate = CurrentDate, TxnPrice = ClosePrice,
TxnQty = UnitSize, TxnFees = 0)
# place an exit order
LastDate <- last(time(SPY))
LastPrice <- as.numeric(Cl(SPY[LastDate,]))
addTxn("buyHold", Symbol = "SPY", TxnDate = LastDate, TxnPrice = LastPrice,
TxnQty = -UnitSize , TxnFees = 0)
updatePortf(Portfolio = "buyHold")
updateAcct(name = "buyHold")
updateEndEq(Account = "buyHold")
chart.Posn("buyHold", Symbol = "SPY")
### 12.3.9 Strategy vs. Market
rets <- PortfReturns(Account = account.st)
rets.bh <- PortfReturns(Account = "buyHold")
returns <- cbind(rets, rets.bh)
charts.PerformanceSummary(returns, geometric = FALSE, wealth.index = TRUE,
main = "Strategy vs. Market")
### 12.3.10 Risk/Return Scatterplot
chart.RiskReturnScatter(returns, Rf = 0, add.sharpe = c(1, 2),
main = "Return vs. Risk", colorset = c("red", "blue"))
### 12.3.11 Relative Performance
for(n in 1:(ncol(returns) - 1)) {
chart.RelativePerformance(returns[, n], returns[, ncol(returns)],
colorset = c("red", "blue"), lwd = 2,
legend.loc = "topleft")
}
### 12.3.12 Portfolio Summary
#' Error
pf <- getPortfolio(portfolio.st)
xyplot(pf$summary, type = "h", col = 4)
### 12.3.13 Order Book
ob <- getOrderBook(portfolio.st)
### 12.3.14 Maximum Adverse Excursion
for(symbol in symbols) {
chart.ME(Portfolio = portfolio.st, Symbol = symbol, type = "MAE",
scale = "percent")
}
### 12.3.15 Maximum Favorable Excursion
for(symbol in symbols) {
chart.ME(Portfolio = portfolio.st, Symbol = symbol, type = "MFE",
scale = "percent")
}
## 12.4 Account Summary
a <- getAccount(account.st)
xyplot(a$summary, type = "h", col = 4)
### 12.4.1 Equity Curve
equity <- a$summary$End.Eq
plot(equity, main = "Equity Curve")
### 12.4.2 Account Performance Summary
ret <- Return.calculate(equity, method = "log")
charts.PerformanceSummary(ret, colorset = bluefocus,
main = "Strategy Performance")
### 12.4.3 Cumulative Returns
rets <- PortfReturns(Account = account.st)
chart.CumReturns(rets, colorset = rich10equal, legend.loc = "topleft",
main="SPDR Cumulative Returns")
### 12.4.4 Distribution Analysis
chart.Boxplot(rets, main = "SPDR Returns", colorset= rich10equal)
### 12.4.5 Annualized Returns
(ar.tab <- table.AnnualizedReturns(rets))
### 12.4.6 Performance Scatter Plot
max.risk <- max(ar.tab["Annualized Std Dev",])
max.return <- max(ar.tab["Annualized Return",])
chart.RiskReturnScatter(rets,
main = "SPDR Performance", colorset = rich10equal,
xlim = c(0, max.risk * 1.1), ylim = c(0, max.return))